package org.goyo.main.comet4j;

import org.codehaus.jackson.map.ObjectMapper;
import org.comet4j.core.CometConnection;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;
import org.comet4j.core.event.ConnectEvent;
import org.comet4j.core.event.DropEvent;
import org.comet4j.core.listener.ConnectListener;
import org.comet4j.core.listener.DropListener;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.services.comet4j.IComet4jService;
import org.goyo.main.web.controller.system.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class CometInit {
  protected Logger logger = LoggerFactory.getLogger(this.getClass());
  SessionRegistry sessionRegistry;
  IComet4jService comet4jService;
 
  public static final String CHANNEL_USER_INFO = "onlineUsers";
  public static final String CHANNEL_USER_CHATING_CONTENT = "user_chating_content";
  public static final String ONLINE_OFFLINE_PROMPT = "online_offline_prompt";
  public static final String TASK_PROMPT = "task_prompt";
  public CometInit(ServletContextEvent sctex) {
    WebApplicationContext rwp = WebApplicationContextUtils.getRequiredWebApplicationContext(sctex.getServletContext());
    this.sessionRegistry= (SessionRegistry)rwp.getBean("sessionRegistry");
    this.comet4jService = (IComet4jService)rwp.getBean("comet4jServiceimpl");
      CometContext context = CometContext.getInstance();
      CometContext cc = CometContext.getInstance();
      CometEngine engine = context.getEngine();
 
      //添加连接监听
      engine.addConnectListener(new ConnectListener() {
          @Override
          public boolean handleEvent(ConnectEvent event) {
 
              CometConnection connection = event.getConn();
              String ip = connection.getClientIp();
              String id = connection.getId();
              
              HttpServletRequest request = connection.getRequest();
              
              SysUser user = null;
              user = (SysUser)SessionUtil.getAttribute("user");
              Long count = 0l;
              ObjectMapper om = new ObjectMapper();
              try {
                if(null!=user){
                  user.setMsgClientId(id);
                  count = comet4jService.getInfoTotal();
                  logger.info("id是：" + id + "的用户连接服务器，ip是：" + ip + ",用户名是：" + user.getUsername());
                  event.getTarget().sendTo(TASK_PROMPT, event.getTarget().getConnection(user.getMsgClientId()), count);
                }
                  event.getTarget().sendToAll(CometInit.ONLINE_OFFLINE_PROMPT, om.writeValueAsString((null==user.getTrueName()||user.getTrueName().length()==0?user.getUserName():user.getTrueName())+"  上线"));
              } catch (Exception e) {
                logger.error(e.getMessage(),e);
                 // e.printStackTrace();
              }
              
              return true;
          }
      });
      
      //添加离线、断线监听
      engine.addDropListener(new DropListener() {
          
          @Override
          public boolean handleEvent(DropEvent event) {
 
              CometConnection connection = event.getConn();
              String ip = connection.getClientIp();
              String id = connection.getId();
              HttpServletRequest request = connection.getRequest();
              SysUser user = null;
              user = (SysUser)SessionUtil.getAttribute("user");
              if(null!=user){
                user.setMsgClientId(null);
                logger.info("id是：" + id + "的用户断开与服务器的连接，ip是："+ ip + ",用户名是：" +user.getUsername());
              }
              ObjectMapper om = new ObjectMapper();
              try {
                  event.getTarget().sendToAll(CometInit.ONLINE_OFFLINE_PROMPT, om.writeValueAsString((null==user.getTrueName()||user.getTrueName().length()==0?user.getUserName():user.getTrueName())+"  下线"));
              } catch (Exception e) {
                logger.error(e.getMessage(),e);
              }
              return true;
          }
      });
      
      //注册信道 
      context.registChannel(ONLINE_OFFLINE_PROMPT);
      context.registChannel(TASK_PROMPT);
      
  }
  
  /**
  * 从cookiek中得到某个 key的取值
  * @param cookies
  * @param cookieName
  * @param defaultValue
  * @return
  */
  public String getCookieValue(Cookie[] cookies, String cookieName, String defaultValue) {
      String result = defaultValue;
      if (cookies != null) {
          for (int i = 0; i < cookies.length; i++) {
              Cookie cookie = cookies[i];
              if (cookieName.equals(cookie.getName())) {
                  return cookie.getValue();
              }
          }
      }
      return result;
  }
  
  public List<SysUser> queryLoginUser(int start,int limit){

    List<Object> slist =sessionRegistry.getAllPrincipals();
    int totalCount=slist.size();
    if(slist.size()==0){
        return null;
    }
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    List<Object> pageList=slist.subList(start,limit>slist.size()?slist.size():limit);
    List<SysUser> users = new ArrayList<SysUser>();
    for(int i=0;i<pageList.size();i++){
        List<SessionInformation> sessionList = sessionRegistry.getAllSessions(pageList.get(i),true); 
        SysUser user=(SysUser)pageList.get(i);
        users.add(user);
        /*for(SessionInformation t:sessionList){
            if(k!=0){
                retVal.append(",");
            }
            retVal.append("{\"id\":\""+k+"\",\"userName\":\""+user.getUsername()+"\",\"sessionId\":\""+t.getSessionId()+"\",\"lastRequest\":\""+sdf.format(t.getLastRequest())+"\"}");
            k=k+1;
        }*/
    }
    return users;
}
  
  
  
}
